package com.yunqi.autovender.activity;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.yunqi.autovender.R;
import com.yunqi.autovender.adapter.StackAdapter;

import java.util.List;

import com.yunqi.autovender.databinding.ActivitySettingsBinding;
import com.yunqi.autovender.model.GlobalData;
import com.yunqi.autovender.view.LoadingDialog;
import com.yunqi.autovender.view.OffLineDialog;
import com.yunqi.autovender.view.SelectPopwindow;
import com.yunqi.autovender.view.SetupDialog;
import com.yunqi.autovender.view.StackModifyDialog;

import google.architecture.common.base.BaseActivity;
import google.architecture.common.util.ToastUtils;
import google.architecture.common.widget.xrecyclerview.XRecyclerView;
import google.architecture.coremodel.callback.StackCallback;
import google.architecture.coremodel.callback.StackItemClickCallback;
import google.architecture.coremodel.constant.ARGConstant;
import google.architecture.coremodel.constant.ARouterPath;
import google.architecture.coremodel.constant.ErrorCode;
import google.architecture.coremodel.constant.EventCode;
import google.architecture.coremodel.datamodel.http.entities.ProductData;
import google.architecture.coremodel.navigator.StackNavigator;
import google.architecture.coremodel.rx.RxBus;
import google.architecture.coremodel.rx.RxEvent;
import google.architecture.coremodel.viewmodel.StackViewModel;
import google.architecture.coremodel.viewmodel.ViewModelProviders;


/**
 * 上下货界面
 */
@Route(path = ARouterPath.SettingsAct)
public class SettingsActivity extends BaseActivity implements StackNavigator {

    ActivitySettingsBinding activitySettingsBinding;
    StackViewModel stackViewModel;
    StackAdapter stackAdapter;
    LoadingDialog loadingDialog;
    private TextWatcher mTextWatcher;
    private int unit, row, column;//板号、行号、列号，默认为0，即为全部

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activitySettingsBinding = DataBindingUtil.setContentView(this, R.layout.activity_settings);
        activitySettingsBinding.setCallback(mStackCallback);
        initData();
    }

    private void initData() {
        stackViewModel = new StackViewModel(this.getApplication());
        stackViewModel.setNavigator(this);
        initRecyclerView();
        initWidgetListener();
    }

    private void initWidgetListener() {
        mTextWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                Log.d(TAG, "------afterTextChanged------s=" + s.toString());
                resetData();
                loadData();

            }
        };
        activitySettingsBinding.editSearch.addTextChangedListener(mTextWatcher);
    }


    private void resetData() {
        unit = 0;
        row = 0;
        column = 0;
    }

    private void initRecyclerView() {
        stackAdapter = new StackAdapter(mStackItemClickCallback);
        activitySettingsBinding.recyclerView.setAdapter(stackAdapter);
        activitySettingsBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        activitySettingsBinding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                stackViewModel.setPage(1);
                loadData();
            }

            @Override
            public void onLoadMore() {
                int page = stackViewModel.getPage();
                page++;
                stackViewModel.setPage(page);
                loadData();
            }
        });
        stackViewModel.loadData(getTerNo());
    }

    private String getTerNo() {
        String terNo = (String) GlobalData.getInstance().getData(ARGConstant.ARG_TERNO);
        return terNo;
    }


    private void loadData() {
        String words = activitySettingsBinding.editSearch.getText().toString();
        if (!TextUtils.isEmpty(words)) {
            stackViewModel.searchDrug(words, getTerNo());
        } else if(unit==0&&row==0&&column==0){
            stackViewModel.loadData(getTerNo());
        }
        else {
            stackViewModel.searchDrugByColumn(getTerNo(), unit, row, column);
        }
    }


    private StackItemClickCallback mStackItemClickCallback = new StackItemClickCallback() {

        @Override
        public void onClick(int position, ProductData.Product productItem, int action) {
            switch (action) {
                case StackItemClickCallback.ACTION_STACK_MODIFY: {
                    StackModifyDialog dialog = new StackModifyDialog(SettingsActivity.this, productItem);
                    dialog.setModifyInterface(new StackModifyDialog.ModifyInterface() {
                        @Override
                        public void onModifyCount(int count) {
                            ProductData.Product product = stackAdapter.getProductList().get(position);
                            product.setDrugQuantity(count);
                            stackAdapter.getProductList().set(position, product);
                            stackAdapter.notifyItemChanged(position + 1, "1");
                            RxEvent rxEvent=new RxEvent();
                            rxEvent.code= EventCode.MODIFY_STACK_CODE;
                            rxEvent.obj=product;
                            RxBus.getIntanceBus().post(rxEvent);
                        }
                    });
                    dialog.show();
                }
                break;
                case StackItemClickCallback.ACTION_STACK_OFFLINE: {
                    OffLineDialog dialog = new OffLineDialog(SettingsActivity.this, productItem) {
                        @Override
                        public void onConfirmDelDrug(ProductData.Product product) {
                            loadingDialog = new LoadingDialog(SettingsActivity.this);
                            loadingDialog.show();
                            if (TextUtils.isEmpty(getTerNo())) {
                                Log.e(TAG, "terNo is empty!");
                                return;
                            }
                            stackViewModel.delDrug(position, getTerNo(), product.getPlanId());
                        }
                    };
                    dialog.show();
                }
                break;

            }

        }
    };
    private StackCallback mStackCallback = new StackCallback() {

        @Override
        public void onClick(View view, int action) {
            switch (action) {
                case ACTION_BACK:
                    finish();
                    break;
                case ACTION_SETUP:
                    SetupDialog setupDialog = new SetupDialog(SettingsActivity.this) {
                        @Override
                        public void onConfigComplied() {
                            ToastUtils.showShortToast("配置参数已修改成功，重新开机后生效！");
                        }
                    };
                    setupDialog.show();
                    break;
                case ACTION_UNIT: {
                    SelectPopwindow selectPopwindow = new SelectPopwindow(SettingsActivity.this, SelectPopwindow.TYPE_UNIT, unit) {
                        @Override
                        protected void onSelected(int index) {
                            unit = index;
                            stackViewModel.searchDrugByColumn(getTerNo(), unit, row, column);
                        }
                    };
                    selectPopwindow.showAsDropDown(view);
                }
                break;
                case ACTION_ROW: {
                    SelectPopwindow selectPopwindow = new SelectPopwindow(SettingsActivity.this, SelectPopwindow.TYPE_ROW, row) {
                        @Override
                        protected void onSelected(int index) {
                            row = index;
                            stackViewModel.searchDrugByColumn(getTerNo(), unit, row, column);
                        }
                    };
                    selectPopwindow.showAsDropDown(view);
                }
                break;
                case ACTION_COLUMN: {
                    SelectPopwindow selectPopwindow = new SelectPopwindow(SettingsActivity.this, SelectPopwindow.TYPE_COLUMN, column) {
                        @Override
                        protected void onSelected(int index) {
                            column = index;
                            stackViewModel.searchDrugByColumn(getTerNo(), unit, row, column);
                        }
                    };
                    selectPopwindow.showAsDropDown(view);
                }
                break;

            }
        }
    };




    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTextWatcher != null)
            activitySettingsBinding.editSearch.removeTextChangedListener(mTextWatcher);
    }

    @Override
    protected void onCountDownFinished() {
    }

    @Override
    protected boolean isStartCountDown() {
        return false;
    }

    @Override
    public void showContent(List<ProductData.Product> list, int page) {
        activitySettingsBinding.recyclerView.refreshComplete();
        if (page == 1) {
            stackAdapter.addProductList(list, false);
        } else {
            stackAdapter.addProductList(list, true);
        }
        //当数量小于每页的数目时表示，每页下一页了
        int size=list.size();
        if(size< StackViewModel.SIZE){
            activitySettingsBinding.recyclerView.setLoadingMoreEnabled(false);
        }
    }

    @Override
    public void onOffLineSuccess(int position) {
        ToastUtils.showShortToast("该商品已成功下架！");
        loadingDialog.dismiss();
        ProductData.Product product = stackAdapter.getProductList().get(position);
        product.setDrugQuantity(0);
        stackAdapter.getProductList().set(position, product);
        stackAdapter.notifyItemChanged(position + 1, "1");
        RxEvent rxEvent=new RxEvent();
        rxEvent.code= EventCode.MODIFY_STACK_CODE;
        rxEvent.obj=product;
        RxBus.getIntanceBus().post(rxEvent);
    }

    @Override
    public void showError(int code, String errorMsg) {
        ToastUtils.showShortToast(errorMsg);
        switch (code) {
            case ErrorCode.FAILED_GET_PRODUCT:
                activitySettingsBinding.recyclerView.refreshComplete();
                break;
            case ErrorCode.FAILED_OFFLINE:
                loadingDialog.dismiss();
                break;
        }
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }
}
